package com.efounder.chat.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterInside;
import com.bumptech.glide.request.RequestOptions;
import com.efounder.chat.R;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.http.OpenEthRequest;
import com.efounder.chat.model.LogoutEvent;
import com.efounder.chat.utils.IdentifyQrCodeManager;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.pansoft.chat.photo.JFPicturePickPhotoWallActivity;
import com.efounder.util.AppContext;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.LogUtils;

import net.sf.json.JSONObject;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_APPID;
import static com.efounder.pansoft.chat.photo.JFMessagePicturePickView.REQUEST_PIC_SELECTE_CODE;

/**
 * 设置收款二维码
 *
 * @author yqs
 */
public class SetMoneyCodeFragment extends BaseFragment implements View.OnClickListener {

    private static final String TAG = "SetMoneyCodeFragment";
    private String type;
    private String imagePath;
    private ImageView ivCode;
    private TextView tvText;
    private IdentifyQrCodeManager identifyQrCodeManager;
    private MultiTransformation multiTransformation;


    public static SetMoneyCodeFragment newInstance(String type) {
        Bundle args = new Bundle();
        args.putString("type", type);
        SetMoneyCodeFragment fragment = new SetMoneyCodeFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.wechatview_fragment_setmoneycode, container, false);
        initView(rootView);
        initData();
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        OpenEthRequest.cannelRequest();
    }

    private void initView(View rootView) {
        ivCode = (ImageView) rootView.findViewById(R.id.iv_code);
        tvText = (TextView) rootView.findViewById(R.id.tv_text);
        ivCode.setOnClickListener(this);
    }

    private void initData() {
        type = getArguments().getString("type");
        identifyQrCodeManager = new IdentifyQrCodeManager();
        multiTransformation = new MultiTransformation(
                new CenterInside(),
                new RoundedCornersTransformation(20, 0,
                        RoundedCornersTransformation.CornerType.ALL));

        if ("weixin".equals(type)) {
            tvText.setText(getString(R.string.set_money_code, ResStringUtil.getString(R.string.chat_we_chat)));
        } else {
            tvText.setText(getString(R.string.set_money_code, ResStringUtil.getString(R.string.chat_pay_for)));
        }

        getData();
    }

    private void getData() {
        OpenEthRequest.getUserEthByImUserId(getActivity(), Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)), new OpenEthRequest.EthUserRequestListener() {
            @Override
            public void onSuccess(User user) {
                if ("weixin".equals(type)) {
                    Glide.with(SetMoneyCodeFragment.this).load(user.getWeixinQrUrl()).apply(new RequestOptions().transform(multiTransformation)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .error(R.drawable.wechatview_set_code_add)).into(ivCode);
                } else {
                    Glide.with(SetMoneyCodeFragment.this).load(user.getZhifubaoQrUrl()).apply(new RequestOptions().transform(multiTransformation)
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .error(R.drawable.wechatview_set_code_add)).into(ivCode);
                }
            }

            @Override
            public void onSuccess(String ethAddress, String publicKey, String RSAPublicKey) {

            }

            @Override
            public void onFail(String error) {
                ToastUtil.showToast(getActivity(), ResStringUtil.getString(R.string.chat_get_info_fail));
            }
        });
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_code) {
            selectPhoto();
        }
    }

    private void selectPhoto() {
        Intent intent = new Intent(getActivity(), JFPicturePickPhotoWallActivity.class);
        intent.putExtra(JFPicturePickPhotoWallActivity.MAX_NUM, 1);//可选择的最大照片数
        intent.putExtra("sendBtnName", getResources().getString(R.string.common_text_confirm));
        intent.putExtra(JFPicturePickPhotoWallActivity.SELECT_MODE, JFPicturePickPhotoWallActivity.MODE_PIC_ONLY);
        startActivityForResult(intent, REQUEST_PIC_SELECTE_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PIC_SELECTE_CODE
                && resultCode == Activity.RESULT_OK) {
            //图库选择照片
            ArrayList<String> arrayList = (ArrayList<String>) data.getExtras().get("mSelectedPics");
            boolean isRawpic = data.getExtras().getBoolean("isRawPic");
            if (arrayList == null) {
                return;
            }
            if (arrayList.size() == 0) {
                return;
            }

            imagePath = arrayList.get(0);
            LoadingDataUtilBlack.show(getActivity(), ResStringUtil.getString(R.string.common_text_checking));

            Glide.with(getActivity()).load(imagePath).apply(new RequestOptions().transform(multiTransformation)).into(ivCode);
            identifyQrCodeManager.scanImage(imagePath, new IdentifyQrCodeManager.ScanCallBack() {
                @Override
                public void scanSuccess(String filePath, String reult) {
                    LoadingDataUtilBlack.dismiss();
                    uploadToCloud(imagePath);
                }

                @Override
                public void scanFail() {
                    LoadingDataUtilBlack.dismiss();
                    showAlert();
                }
            });

//            uploadToServer(imagePath);
        }


    }

    private void showAlert() {
        new AlertDialog.Builder(getActivity()).setTitle(R.string.common_text_hint).setMessage(ResStringUtil.getString(R.string.chat_no_find_again))
                .setPositiveButton(R.string.chat_okay, null).create().show();
    }

    //上传服务器
    private void uploadToCloud(String imagePath) {
        LoadingDataUtilBlack.show(getActivity(), ResStringUtil.getString(R.string.common_text_uploading));
        PansoftCloudUtil.getCloudRes(imagePath, new PansoftCloudUtil.UpLoadListener() {
            @Override
            public void getHttpUrl(Boolean isSuccess, String url) {
                if (isSuccess) {
                    uploadToServer(url);
                } else {
                    LoadingDataUtilBlack.dismiss();
                    ToastUtil.showToast(getActivity(), R.string.common_text_upload_fail);
                }
            }
        });


    }

    private void uploadToServer(String imageUrl) {

        String method = "updateUserWeChatQRCode";
        HashMap<String, String> map = new HashMap<>();
        LogUtils.i(imageUrl);
        if ("weixin".equals(type)) {
            map.put("weChatQRCode", imageUrl);
        } else {
            map.put("aliPayQRCode", imageUrl);
            method = "updateUserAliPayQRCode";
        }

        String baseUrl = EnvironmentVariable.getProperty("TalkChainUrl") + "/tcserver/user/" + method;
        map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        JFCommonRequestManager.getInstance()
                .requestGetByAsyn(TAG, baseUrl, map, new JFCommonRequestManager.ReqCodeCallBack<String>() {
                    @Override
                    public void onReqFailed(int errorCode, String errorMsg) {
                        LoadingDataUtilBlack.dismiss();
                        ToastUtil.showToast(getActivity(), R.string.chat_set_fail_abnormal);
                        //todo 针对区块链应用，如果errorcode =400 表示用户登录失效，需要重新登录 yqs
                        if (errorCode == 400 && EnvironmentVariable.getProperty(KEY_SETTING_APPID, "").equals(AppContext.getInstance()
                                .getString(R.string.special_appid))) {
                            //发送弹框提示用户
                            EventBus.getDefault().post(new LogoutEvent(LogoutEvent.TYPE_LOGIN_OUT_OF_DATE));
                        }
                    }

                    @Override
                    public void onReqSuccess(String result) {
                        LoadingDataUtilBlack.dismiss();
                        //{"result":"success"}
                        JSONObject jsonObject = JSONObject.fromObject(result);
                        if (jsonObject.optString("result", "").equals("success")) {
                            ToastUtil.showToast(getActivity(), R.string.chat_set_success);
                        } else {
                            ToastUtil.showToast(getActivity(), R.string.chat_set_fail);
                        }


                    }

                    @Override
                    public void onReqFailed(String errorMsg) {
                    }
                });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        identifyQrCodeManager.realease();
    }
}
